import Vue from "vue";
import { login, getInfo, logout } from "@/api/login";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { welcome } from "@/utils/util";

const user = {
  state: {
    token: "",
    name: "",
    welcome: "",
    avatar: "",
    roles: 0,
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name;
      state.welcome = welcome;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_INFO: (state, info) => {
      state.info = info;
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            // console.info(response);
            const result = response.CustomHttpResponseBody;
            Vue.ls.set(
              ACCESS_TOKEN,
              result.elementAuthority,
              7 * 24 * 60 * 60 * 1000
            );
            commit("SET_TOKEN", result.elementAuthority);
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 获取登录用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(response => {
            const result = response.CustomHttpResponseBody.body;
            commit("SET_ROLES", response.CustomHttpResponseBody.elementAuthority);
            commit("SET_INFO", result);

            commit("SET_NAME", {
              name: result.nickName,
              welcome: welcome()
            });
            commit("SET_AVATAR", result.avatarUrl);

            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise(resolve => {
        commit("SET_TOKEN", "");
        commit("SET_ROLES", []);
        Vue.ls.remove(ACCESS_TOKEN);

        logout(state.token)
          .then(() => {
            resolve();
          })
          .catch(() => {
            resolve();
          });
      });
    }
  }
};

export default user;
